from ui.components.base.widget import TgBaseWidget
from .views.margin_trading_view import MarginTradingView
from .controllers.margin_trading_controller import MarginTradingController
from loguru import logger


class MarginTradingTab(TgBaseWidget):
    """融资融券 Tab - MVC架构重构版本"""

    def __init__(self):
        super().__init__()
        self.view = MarginTradingView()
        self.controller = MarginTradingController()
        
        self._setup_mvc()
        self._initialize()

    def _setup_mvc(self):
        from ui.components.layouts.vbox_layout import TgVBoxLayout
        TgVBoxLayout(self).addWidget(self.view)
        self._connect_signals()

    def _connect_signals(self):
        self.view.query_button.clicked.connect(self._on_query_clicked)
        
        self.controller.data_loaded.connect(self.view.update_chart_data)
        self.controller.loading_state_changed.connect(self.view.set_query_loading)

    def _initialize(self):
        start_date, end_date = self.controller.get_default_date_range()
        self.view.set_default_dates(start_date, end_date)

    def _on_query_clicked(self):
        start_date, end_date = self.view.get_date_range()
        logger.info(f"开始查询融资融券数据，起始时间：{start_date}，结束时间：{end_date}")
        self.controller.load_chart_data(start_date, end_date)

    def cleanup(self):
        """清理资源"""
        self.view.clear_all_charts()